<template>
  <div ref="content">
    <div class="search">
      <input type="text" v-model="keywords" class="search-input" placeholder="输入城市名" />
    </div>
    <div class="search-content" ref="wrapper" v-show='keywords.length'>
      <div>
        <ul v-for="item of list" :key="item.id">
          <li class="search-item" @click='handleCityClick(item.name)'>{{item.name}}</li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script>
import Bscroll from "better-scroll";
export default {
  props: {
    cities: Object
  },
  data() {
    return {
      keywords: "",
      list: [],
      timer: null
    };
  },
  methods:{
    handleCityClick(city){
      this.$store.dispatch('changeCity', city);
      this.$router.push('/')
      // this.keywords = '';
    }
  },
  watch: {
    keywords() {
      if (this.timer) {
        clearTimeout(timer);
      } else {
        setTimeout(() => {
          var result = [];
          for (var key in this.cities) {
            this.cities[key].forEach(item => {
              if (
                item.spell.indexOf(this.keywords) > -1 ||
                item.name.indexOf(this.keywords) > -1
              ) {
                result.push(item);
              }
            });
          }
          this.list = result;
        }, 100);
      }
    }
  },
  mounted() {
    this.scroll = new Bscroll(this.$refs.wrapper);
  }
};
</script>
<style lang="stylus" scoped>
@import '~@/assets/style/varibles.styl';

.search {
  height: 0.72rem;
  background: $bgColor;
  padding: 0 0.1rem;

  .search-input {
    box-sizing: border-box;
    width: 100%;
    height: 0.62rem;
    line-height: 0.62rem;
    border-radius: 0.6rem;
    text-align: center;
    margin-top: 0.05rem;
    padding: 0 0.1rem;
  }
}

.search-content {
  position: absolute;
  top: 1.58rem;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  z-index: 1;
  overflow: hidden;
}

.search-item {
  height: 0.6rem;
  line-height: 0.6rem;
  border-bottom: 1px solid #eee;
  padding-left: 0.2rem;
}
</style>
